package com.zbkj.crmeb.merchant.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.CommonPage;
import com.common.PageParamRequest;
import com.constants.Constants;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.utils.DateUtil;
import com.utils.vo.dateLimitUtilVo;
import com.zbkj.crmeb.finance.service.UserExtractService;
import com.zbkj.crmeb.merchant.admin.service.MerRetailShopService;
import com.zbkj.crmeb.store.request.RetailShopRequest;
import com.zbkj.crmeb.store.request.RetailShopStairUserRequest;
import com.zbkj.crmeb.store.response.RetailShopResponse;
import com.zbkj.crmeb.store.response.RetailShopTopResponse;
import com.zbkj.crmeb.store.response.RetailShopUserOrderResponse;
import com.zbkj.crmeb.store.response.RetailShopUserResponse;
import com.zbkj.crmeb.store.service.StoreOrderService;
import com.zbkj.crmeb.store.service.UserCommissionService;
import com.zbkj.crmeb.system.service.SystemConfigService;
import com.zbkj.crmeb.user.dao.UserDao;
import com.zbkj.crmeb.user.model.User;
import com.zbkj.crmeb.user.request.UserSearchRequest;
import com.zbkj.crmeb.user.response.UserResponse;
import com.zbkj.crmeb.user.service.UserBillService;
import com.zbkj.crmeb.user.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Classname RetailShopServiceImpl
 * @Description 分销业务实现
 * @Date 2020/6/22 11:20 上午
 * @Created by stivepeim
 */
@Service
public class MerRetailShopServiceImpl extends ServiceImpl<UserDao, User> implements MerRetailShopService {

    @Resource
    private UserDao userDao;

    @Autowired
    private UserService userService;

    @Autowired
    private UserExtractService userExtractService;

    @Autowired
    private StoreOrderService storeOrderService;

    @Autowired
    private UserBillService userBillService;

    @Autowired
    private SystemConfigService systemConfigService;

    @Autowired
    private UserCommissionService userCommissionService;

    /**
     * 获取分销列表
     * @param keywords
     * @param dateLimit
     * @param pageRequest
     * @return
     */
    @Override
    public PageInfo<RetailShopUserResponse> getList(String keywords, String dateLimit, PageParamRequest pageRequest) {
        Page<User> pageUserPage = PageHelper.startPage(pageRequest.getPage(), pageRequest.getLimit());

//        User currentUser = userService.getUserByEntity();
        UserSearchRequest userSearchRequest = new UserSearchRequest();
        userSearchRequest.setStatus(true);
        userSearchRequest.setIsPromoter(true);
        userSearchRequest.setKeywords(keywords);
        userSearchRequest.setData(dateLimit);
        PageInfo<UserResponse> userResponses = userService.getList(userSearchRequest,pageRequest);
        List<RetailShopUserResponse> retailShopUserResponses = new ArrayList<>();
        for (UserResponse rp:userResponses.getList()) {
            RetailShopUserResponse nrp = new RetailShopUserResponse(
                    rp.getUid(),rp.getAccount(),rp.getPwd(),rp.getRealName(),rp.getBirthday(),rp.getCardId(),rp.getMark(),
                    rp.getPartnerId(),rp.getGroupId(),rp.getGroupName(),rp.getTagName(),rp.getNickname(),rp.getAvatar(),rp.getPhone(),
                    rp.getAddIp(),rp.getLastIp(),rp.getNowMoney(),rp.getBrokeragePrice(),rp.getIntegral(),rp.getExperience(),rp.getSignNum(),
                    rp.getStatus(),rp.getLevel(),rp.getSpreadUid(),rp.getSpreadTime(),rp.getSpreadNickname(),rp.getUserType(),rp.getIsPromoter(),
                    rp.getPayCount(),rp.getSpreadCount(),rp.getAddres(),rp.getAdminid(),rp.getLoginType(),rp.getUpdateTime(),rp.getCreateTime(),
                    rp.getLastLoginTime(),rp.getCleanTime(),null,null);
            retailShopUserResponses.add(nrp);
        }

        for (RetailShopUserResponse rShopUser:retailShopUserResponses) {
            // 推广用户数量
//            List<Integer> userIds = new ArrayList<>();
            List<Integer> userIds = userResponses.getList().stream().map(e -> {
                return e.getUid();
            }).collect(Collectors.toList());
//            userIds.add(currentUser.getUid());
//            rShopUser.setSpreadPeopleCount(userService.getSpreadPeopleIdList(userIds).size());
            rShopUser.setSpreadPeopleCount(userService.getSpreadPeopleIdList(userIds).size());
            // 获取提现数据
            rShopUser.setUserExtractResponse(userExtractService.getUserExtractByUserId(rShopUser.getUid()));
            // 获取订单数据
            rShopUser.setRetailShopOrderDataResponse(storeOrderService.getOrderDataByUserId(rShopUser.getUid()));
            // 佣金数据
            rShopUser.setBrokerageMoney(userBillService.getDataByUserId(rShopUser.getUid()));
        }
        return CommonPage.copyPageInfo(pageUserPage, retailShopUserResponses);
    }

    /**
     * 获取分销头部数据
     * @param nickName 查询参数
     * @param dateLimit 时间参数对象
     */
    @Override
    public List<UserResponse> getStatisticsData(String nickName, String dateLimit) {
        UserSearchRequest request = new UserSearchRequest();
        request.setIsPromoter(true);
        request.setData(dateLimit);
        request.setKeywords(nickName);

        PageParamRequest pageParamRequest = new PageParamRequest();
        pageParamRequest.setLimit(1);

        PageInfo<UserResponse> list = userService.getList(request, pageParamRequest);
        return list.getList();
    }

    /**
     * 统计推广人员列表
     * @param request 查询参数
     * @return 推广人员集合列表
     */
    @Override
    public PageInfo<User> getStairUsers(RetailShopStairUserRequest request, PageParamRequest pageParamRequest) {
        return userService.getUserListBySpreadLevel(request, pageParamRequest);
    }

    /**
     * 获取分销配置信息
     * @return 返回配置信息
     */
    @Override
    public RetailShopRequest getManageInfo(Integer merId) {
        List<String> keys = initKeys(merId);
        RetailShopRequest response = new RetailShopRequest();
        response.setStoreBrokerageStatus(systemConfigService.getValueByKey(keys.get(1)));
        response.setStoreBrokerageRatio(systemConfigService.getValueByKey(keys.get(2)));
        response.setStoreBrokerageTwo(systemConfigService.getValueByKey(keys.get(3)));
        response.setUserExtractMinPrice(systemConfigService.getValueByKey(keys.get(4)));
        response.setExtractTime(systemConfigService.getValueByKey(keys.get(6)));
        return response;
    }

    /**
     * 更新分销配置信息
     * @param retailShopRequest 待保存数据
     * @return 更新结果
     */
    @Override
    public boolean setManageInfo(RetailShopRequest retailShopRequest) {
        List<String> keys = initKeys(retailShopRequest.getMerId());
        systemConfigService.updateOrSaveValueByName(keys.get(1), retailShopRequest.getStoreBrokerageStatus());
        systemConfigService.updateOrSaveValueByName(keys.get(2), retailShopRequest.getStoreBrokerageRatio());
        systemConfigService.updateOrSaveValueByName(keys.get(3), retailShopRequest.getStoreBrokerageTwo());
        systemConfigService.updateOrSaveValueByName(keys.get(4), retailShopRequest.getUserExtractMinPrice());
        systemConfigService.updateOrSaveValueByName(keys.get(6), retailShopRequest.getExtractTime());
        return true;
    }

    @Override
    public RetailShopResponse getRetailShopList(UserSearchRequest userSearchRequest, PageParamRequest pageRequest) {
        PageInfo<UserResponse> userResponses = userService.getList(userSearchRequest,pageRequest);
        //获取推广订单信息
        if (!CollectionUtils.isEmpty(userResponses.getList())){
            userResponses.getList().forEach(userResponse -> {
                User promotionalInformation = userService.getPromotionalInformation(userResponse.getUid());
                userResponse.setSpreadCount(promotionalInformation.getSpreadCount());
                userResponse.setDistributionOrders(promotionalInformation.getDistributionOrders());
                userResponse.setDistributionPrice(promotionalInformation.getDistributionPrice());
            });
        }

        //获取头部数据
        List<User> userList = userService.getUserResponseList(userSearchRequest);
        RetailShopTopResponse retailShopTopResponse = RetailShopTopResponse.builder()
                .distributorsNumber(userList.size())
                .promotedUsers(userList.stream().filter(user -> Objects.nonNull(user.getSpreadCount())).mapToInt(User::getSpreadCount).sum())
                .promotionOrders(userList.stream().filter(user -> Objects.nonNull(user.getDistributionOrders())).mapToInt(User::getDistributionOrders).sum())
                .orderPaidAmount(userList.stream().map(User::getDistributionPrice).filter(Objects::nonNull).reduce(BigDecimal.ZERO,BigDecimal::add))
                .canWithdrawnAmount(userList.stream().map(User::getWithdrawalPrice).filter(Objects::nonNull).reduce(BigDecimal.ZERO,BigDecimal::add))
                .withdrawnAmount(userList.stream().map(User::getClosePrice).filter(Objects::nonNull).reduce(BigDecimal.ZERO,BigDecimal::add))
                .frozenAmount(userList.stream().map(User::getFrozenPrice).filter(Objects::nonNull).reduce(BigDecimal.ZERO,BigDecimal::add)).build();

        if (!CollectionUtils.isEmpty(userList)){
            //查询推广人
            List<Integer> uidList = userList.stream().map(User::getUid).collect(Collectors.toList());
            List<User> userList1 = userDao.selectList(new LambdaQueryWrapper<>(User.class).in(User::getSpreadUid,uidList).eq(User::getMerId,userSearchRequest.getMerId()));
            List<Integer> uidList1 = userList1.stream().map(User::getUid).collect(Collectors.toList());
            List<User> userList2 = new ArrayList<>();
            if (!CollectionUtils.isEmpty(uidList1)){
                userList2 = userDao.selectList(new LambdaQueryWrapper<>(User.class).in(User::getSpreadUid,uidList1).eq(User::getMerId,userSearchRequest.getMerId()));
            }
            userList1.addAll(userList2);
            retailShopTopResponse.setPromotedUsers((int) userList1.stream().distinct().count());
            //查询推广订单数量
            RetailShopTopResponse promotionOrder = userCommissionService.getPromotionOrder(uidList);
            retailShopTopResponse.setPromotionOrders(promotionOrder.getPromotionOrders());
            retailShopTopResponse.setOrderPaidAmount(promotionOrder.getOrderPaidAmount());
        }

        RetailShopResponse retailShopResponse = new RetailShopResponse();
        retailShopResponse.setList(CommonPage.restPage(userResponses));
        retailShopResponse.setTop(retailShopTopResponse);
        return retailShopResponse;
    }

    @Override
    public PageInfo<User> getUserListBySpreadLevel(RetailShopStairUserRequest request, PageParamRequest pageParamRequest) {
        Page<User> userPage = PageHelper.startPage(pageParamRequest.getPage(),pageParamRequest.getLimit());
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        if(StringUtils.isNotBlank(request.getDateLimit())){
            dateLimitUtilVo dateLimit = DateUtil.getDateLimit(request.getDateLimit());
            lqw.between(User::getCreateTime,dateLimit.getStartTime(),dateLimit.getEndTime());
        }
        if(StringUtils.isNotBlank(request.getNickName())){
            lqw.and(i -> i.like(User::getNickname, request.getNickName())
                    .or().eq(User::getPhone, request.getNickName())
                    .or().eq(User::getUid, request.getNickName()));
        }
        //判断上一级是否包含uid
        String type = "/" + request.getUid() + "/";
        lqw.like(User::getPath, type);
        if (Objects.equals(1,request.getType())){
            lqw.last("and locate('" + type + "',path) = 1");
        }else if (Objects.equals(2,request.getType())) {
            lqw.last("and locate('" + type + "',path) > 1");
        }
        List<User> userList = userDao.selectList(lqw);
        if (!CollectionUtils.isEmpty(userList)){
            userList.stream().forEach(user -> {
                User promotionalInformation = userService.getPromotionalInformation(user.getUid());
                user.setSpreadCount(promotionalInformation.getSpreadCount());
                user.setDistributionOrders(promotionalInformation.getDistributionOrders());
                user.setDistributionPrice(promotionalInformation.getDistributionPrice());
            });
        }
        return CommonPage.copyPageInfo(userPage, userList);
    }

    @Override
    public PageInfo<RetailShopUserOrderResponse> getOrderListBySpreadLevel(RetailShopStairUserRequest request, PageParamRequest pageParamRequest) {
        Page<User> userPage = PageHelper.startPage(pageParamRequest.getPage(),pageParamRequest.getLimit());
        if(StringUtils.isNotBlank(request.getDateLimit())){
            dateLimitUtilVo dateLimit = DateUtil.getDateLimit(request.getDateLimit());
            request.setStartTime(DateUtil.strToDate(dateLimit.getStartTime(), Constants.DATE_FORMAT));
            request.setEndTime(DateUtil.strToDate(dateLimit.getEndTime(), Constants.DATE_FORMAT));
        }
        return userCommissionService.getOrderListBySpreadLevel(request,pageParamRequest);
    }

    ///////////////////////////////////////////////////// 自定义

    public List<String> initKeys(Integer merId){
        List<String> keys = new ArrayList<>();
        keys.add("brokerage_func_status_"+merId);
        keys.add("store_brokerage_status_"+merId);
        keys.add("store_brokerage_ratio_"+merId);
        keys.add("store_brokerage_two_"+merId);
        keys.add("user_extract_min_price_"+merId);
        keys.add("user_extract_bank_"+merId);
        keys.add("extract_time_"+merId);
        keys.add("store_brokerage_price_"+merId);
        keys.add("brokerage_bindind_"+merId);
        return keys;
    }
}
